package cn.edu.bupt.fluxdemo.controller;

import cn.edu.bupt.fluxdemo.service.UserMessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import java.time.Duration;

@RestController
@RequestMapping("/api/messages")
public class MessageController {
    @Autowired
    private UserMessageService messageService;

    // 长轮询接口
    @GetMapping(value = "/poll", produces = MediaType.APPLICATION_JSON_VALUE)
    public Mono<ResponseEntity<String>> pollMessage(
            @RequestParam String userId,
            @RequestParam(defaultValue = "30000") long timeoutMs) {
        return messageService.waitForMessage(userId, Duration.ofMillis(timeoutMs))
                .map(message -> {
                    if (message.isEmpty()) {
                        return ResponseEntity.status(HttpStatus.NO_CONTENT).body("No messages");
                    } else {
                        return ResponseEntity.ok(message);
                    }
                });
    }

    // 模拟发送消息（测试用）
    @GetMapping("/send")
    public void sendMessage(@RequestParam String userId, @RequestParam String message) {
        messageService.addMessage(userId, message);
    }
}